<template>
  <div>
    <h2>Ajax 模拟请求json-server 数据</h2>
    <h2>word -- {{ word }}</h2>
    <button @click="getList">获取list</button>
    <div>
      <h4 v-for="(l, i) in list" :key="i">{{ l }}</h4>
    </div>
    <div>
      <h2>用户列表</h2>
      <ul>
        <li v-for="(l, i) in user" :key="i">
          名字：{{ l.username }}/ 年龄：{{ l.age }}
          <button @click="deleteOne(l,i)">删除</button>
          <button @click="updateOne(l,i)">修改</button>
        </li>
      </ul>
      <h2>添加用户</h2>
      <p>
        <input type="text" v-model="form.username" placeholder="请输入姓名：" />
      </p>
      <p>
        <input type="text" v-model.number="form.age" placeholder="请输入年龄" />
      </p>
      <p><button @click="addUser">添加</button></p>
    </div>
  </div>
</template>


<script>
export default {
  data() {
    return {
      word: "Hello  word",
      list: [],
      user: [],
      form: {},
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    getList() {
      $.get("http://localhost:3000/list").then((res) => {
        this.list = res;
      });
    },
    getUser() {
      $.ajax({
        url: "http://localhost:3000/user",
        type: "get",
        success: (res) => {
          console.log(res);
          this.user = res;
        },
      });
    },
    deleteOne(l, i) {
      $.ajax({
        url: "http://localhost:3000/user/" + l.id,
        type: "delete", // 请求方式
        success: (res) => {
          console.log(res);
          this.user.splice(i, 1);
        },
      });
    },
    updateOne(l, i) {
      let value = window.prompt(i, l.username);
      console.log(value);
      if (value != null) {
        $.ajax({
          url: "http://localhost:3000/user/" + l.id,
          type: "PATCH",
          data: {
            username: value,
          },
          success: (res) => {
            l.username = value;
            this.user.splice(i, 1, l);
          },
        });
      }
    },
    addUser() {
      if (this.form.username) {
        $.post("http://localhost:3000/user", this.form).then((res) => {
          this.form = {};
          this.getUser();
        });
      }
    },
  },
  mounted() {
    $.ajax({
      url: "http://localhost:3000/test",
      type: "GET",
      success: (res) => {
        console.log(res);
        this.word = res[0];
      },
    });
  },
};
</script>